package org.senseframework.support.orm.mybatis.query.builder;

import org.apache.commons.beanutils.PropertyUtils;
import org.senseframework.support.orm.mybatis.definition.EntityColumnDefinition;
import org.senseframework.support.orm.mybatis.definition.EntityDefinition;
import org.senseframework.support.orm.mybatis.definition.Update;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Author lanjian
 * Email  jianlan@iflytek.com
 */
public class InsertBuilder extends BaseQuery {

    private static Logger logger = LoggerFactory.getLogger(InsertBuilder.class);

    public static InsertBuilder build(Class clazz) {
        return new InsertBuilder(clazz);
    }

    protected InsertBuilder(Class clazz) {
        super(clazz);
    }

    private List<Update> updates = new ArrayList<Update>();

    public List<Update> getUpdates() {
        return updates;
    }

    public void setUpdates(List<Update> updates) {
        this.updates = updates;
    }


    public InsertBuilder set(Object object) {
        if (!getClazz().equals(object.getClass())) {
            throw new RuntimeException("不支持该类");
        }
        EntityDefinition entityDefinition = findEntityDefinition();
        List<Field> all = allFields(getClazz());
        for (Field field : all) {
            EntityColumnDefinition entityColumnDefinition = entityDefinition.getColumnDefinitions().get(field.getName());
            if (entityColumnDefinition != null) {
                try {
                    Object obj = PropertyUtils.getProperty(object, entityColumnDefinition.getJavaColumn());
                    if (obj != null) {
                        set(field.getName(), obj);
                    }
                } catch (Exception e) {
                    logger.info("set object", e);
                }
            }
        }
        return this;
    }

    public InsertBuilder set(String property, Object value) {
        set(property, value, updates, this);
        return this;
    }
}
